import os
import json
from openai import OpenAI
from src.utils.logger import log_info, log_error
from src.modules.file_manager import FileManager

class OpenAIProcessor:
    """管理AI服务调用的类，允许不同实例使用不同的API密钥"""
    
    def __init__(self, api_key=None, logger=None):
        """
        初始化OpenAI处理器
        
        :param api_key: OpenAI API密钥，如果为None则尝试从环境变量或配置文件获取
        :param logger: 日志记录函数
        """
        self.logger = logger
        self.file_manager = FileManager(logger=logger)
        self._client = None
        
        # 获取API密钥
        self.api_key = api_key
        
        # 如果未提供API密钥，尝试从环境变量或配置文件获取
        if not self.api_key:
            self.api_key = os.environ.get("OPENAI_API_KEY")
            
        if not self.api_key:
            try:
                with open("config.json", "r") as f:
                    config = json.load(f)
                    self.api_key = config.get("openai_api_key")
            except Exception as e:
                self._log(f"无法从配置文件读取API密钥: {str(e)}", level="warning")
        
    def _log(self, message, level="info"):
        """记录日志"""
        if self.logger:
            self.logger(message, level=level)
        elif level == "error":
            log_error(message)
        else:
            log_info(message)
    
    @property
    def client(self):
        """获取OpenAI客户端"""
        if self._client is None:
            if not self.api_key:
                raise ValueError("OpenAI API密钥未设置")
                
            self._client = OpenAI(api_key=self.api_key)
            
        return self._client
    
    def transcribe_audio(self, audio_path, language=None):
        """
        使用Whisper API转录音频为文本
        
        :param audio_path: 音频文件路径
        :param language: 语言代码 (可选)
        :return: 转录文本
        """
        try:
            self._log(f"开始转录音频: {os.path.basename(audio_path)}")
            
            with open(audio_path, "rb") as audio_file:
                options = {
                    "file": audio_file,
                    "model": "whisper-1", 
                    "response_format": "text"
                }
                
                if language:
                    options["language"] = language
                    
                response = self.client.audio.transcriptions.create(**options)
                
            self._log("音频转录完成")
            return {
                "success": True, 
                "text": response
            }
                
        except Exception as e:
            error_message = f"音频转录失败: {str(e)}"
            self._log(error_message, level="error")
            return {
                "success": False,
                "message": error_message
            }
    
    def generate_text(self, prompt, model="gpt-3.5-turbo", temperature=0.7, max_tokens=1000):
        """
        使用ChatGPT生成文本
        
        :param prompt: 提示词
        :param model: 模型名称
        :param temperature: 温度参数
        :param max_tokens: 最大令牌数
        :return: 生成的文本
        """
        try:
            self._log(f"开始使用{model}生成文本")
            
            response = self.client.chat.completions.create(
                model=model,
                messages=[
                    {"role": "system", "content": "你是一位专业的文案撰写专家。"},
                    {"role": "user", "content": prompt}
                ],
                temperature=temperature,
                max_tokens=max_tokens
            )
            
            text = response.choices[0].message.content.strip()
            
            self._log("文本生成完成")
            return {
                "success": True,
                "text": text
            }
            
        except Exception as e:
            error_message = f"文本生成失败: {str(e)}"
            self._log(error_message, level="error")
            return {
                "success": False,
                "message": error_message
            }
    
    def extract_audio_from_video(self, video_path):
        """
        从视频中提取音频（用于Whisper API）
        
        :param video_path: 视频文件路径
        :return: 音频文件路径
        """
        try:
            import subprocess
            from datetime import datetime
            
            self._log(f"开始从视频提取音频: {os.path.basename(video_path)}")
            
            # 创建临时文件路径
            temp_file = self.file_manager.create_temp_file(
                prefix="audio_",
                suffix=".mp3"
            )
            audio_path = temp_file.path
            
            # 使用FFmpeg提取音频
            cmd = [
                "ffmpeg",
                "-i", video_path,
                "-q:a", "0",
                "-map", "a",
                "-y",
                audio_path
            ]
            
            startupinfo = None
            if os.name == 'nt':
                # 在Windows上隐藏命令窗口
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                
            process = subprocess.run(
                cmd,
                startupinfo=startupinfo,
                stderr=subprocess.PIPE,
                stdout=subprocess.PIPE,
                universal_newlines=True
            )
            
            if process.returncode != 0:
                raise Exception(f"FFmpeg执行失败: {process.stderr}")
                
            self._log(f"音频提取成功: {os.path.basename(audio_path)}")
            return {
                "success": True,
                "audio_path": audio_path
            }
            
        except Exception as e:
            error_message = f"音频提取失败: {str(e)}"
            self._log(error_message, level="error")
            return {
                "success": False,
                "message": error_message
            }